//
//  DamageReportViewController.m
//  Project6
//
//  Created by ToanDK on 11/14/12.
//  Copyright (c) 2012 DungNP. All rights reserved.
//
#define kPhotoCompressionRate 0.4

#import "DamageReportViewController.h"
#import "ViewController.h"

#import "DistanceCell.h"
#import "DistanceCell2.h"
#import "DamageReportButtonsCell.h"
#import "TextViewCell.h"
#import "EnterDataCell.h"
#import "SaveSummaryCell.h"
#import "SuppendFinishCell.h"
#import "NSData+Base64.h"

#import "MBProgressHUD.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJson.h"

#import "DBProcessing.h"

@implementation DamageReportViewController
@synthesize ReportDictInfo;
@synthesize distanceMaxLength;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(int)getDamageTypeIndex:(NSString *) damageType
{
    for (int i=0; i< DamageItems.count; i++) {
        if ([damageType isEqualToString:[DamageItems objectAtIndex:i]]) {
            return i;
        }
    }
    
    return 0;
}

- (void) keyboardDidShow:(NSNotification*)notification {
    CGRect keyboardFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSLog(@"keyboard frame raw %@", NSStringFromCGRect(keyboardFrame));
    
    // Xac dinh text field dang o row nao section nao
    //    NSLog(@"textField.tag:%d",textField.tag);
    if(!tableISRESIZED)
    {
        tblDamageReportTable.frame = CGRectMake(tblDamageReportTable.frame.origin.x,tblDamageReportTable.frame.origin.y, tblDamageReportTable.frame.size.width, tblDamageReportTable.frame.size.height-keyboardFrame.size.height);
        // raise flag
        tableISRESIZED = TRUE;
    }

  
}

//-(void) viewWillDisappear:(BOOL)animated {
//    if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) {
//        // back button was pressed.  We know this is true because self is no longer
//        // in the navigation stack.
//        [self backNavigationTapped];
//    }
//    [super viewWillDisappear:animated];
//}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // LeftButton in Navigation Bar
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithTitle:@"Back"
                                                                      style:UIBarButtonItemStylePlain
                                                                     target:self action:@selector(backNavigationTapped)];
    self.navigationItem.leftBarButtonItem = leftBarButton;
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
    
    // init base64photos
    base64Photos = [[NSMutableArray alloc] initWithCapacity:0]; // get from library or take by camera
    //    activeTextFields = [[NSMutableArray alloc] initWithCapacity:0];
    activeTextFiledInfo =[[NSMutableDictionary alloc] initWithCapacity:0];
    //activeTextFieldIndexPath =[[NSMutableArray alloc] initWithCapacity:0];
    savedDamageRecords =[[NSMutableArray alloc] initWithCapacity:0];
    
    // set background for table
    [tblDamageReportTable setBackgroundView:nil];
    UIView * bgView = [[UIView alloc] initWithFrame:tblDamageReportTable.frame];
    bgView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"greyBackground.png"]];
    [tblDamageReportTable setBackgroundView:bgView];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backgroundTapped)];
    [tblDamageReportTable addGestureRecognizer:tapGesture];
    tapGesture.cancelsTouchesInView = NO;
    
    self.title = @"Damage report";
    // Do any additional setup after loading the view from its nib.
    // init header sections
    sectionNames = [[NSArray alloc] initWithObjects:
                    @"Distance",                //0
                    @"Damage",                  //1
                    @"Cause",                   //2
                    @"Length (mm)",                  //3
                    @"Width/Diameter (mm)",     //4
                    @"Area(% of Blade Surface)", //5
                    @"Depth (mm)",               //6
                    @"Rating",                  //7
                    @"Notes",                   //8
                    @"Actions",                 //9
                    @"",                        //10 Detail Save
                    @"",                        //11 second part of actions
                     @"Area",                    //12 Area
                    nil];
    // init content rows
    contentRows = [[NSMutableArray alloc] initWithObjects:
                  @"",                //0
                  @"Rub mark",                  //1
                  @"Post commisioning",                   //2
                  @"",                  //3
                  @"",     //4
                  @"", //5
                  @"",               //6
                  @"",                  //7
                  @"",                   //8
                  @"",                 //9
                  @"",                        //Detail Save
                  @"",                        //second part of actions
                  @"",                    // area
                  nil];
    

    
    heighOfRowOnSections = [[NSArray alloc] initWithObjects:
                            @"40",
                            @"40",
                            @"40",
                            @"40",
                            @"40",
                            @"40",
                            @"40",
                            @"40",
                            @"120",
                            @"40",
                            @"120",
                            @"40",
                            @"40",
                            nil];
    
    headerSectionIndexs = [[NSMutableArray alloc] initWithObjects:
                           @"0",
                           @"12",
                           @"1",
                           @"2",
                           @"3",
                           @"4",
                           @"6",
                           @"8",
                           @"9",
                           @"11",
                           nil];
    currentSaveSection = 0;
    //indexOfFirstSaveSection = 8;
    indexOfFirstSaveSection = 9;
    
    // init combobox Damage items
    DamageItems = [[NSMutableArray alloc] initWithCapacity:0];
    [DamageItems addObject:@"Rub mark"];
    [DamageItems addObject:@"Scratch"];
    [DamageItems addObject:@"Gel coat crack"];
    [DamageItems addObject:@"Bubble"];
    [DamageItems addObject:@"Fissures/holes"];
    [DamageItems addObject:@"Chip"];
    [DamageItems addObject:@"Cast"];
    [DamageItems addObject:@"Delamination"];
    [DamageItems addObject:@"Water in blade"];
    [DamageItems addObject:@"Oil in blade"];
    [DamageItems addObject:@"Tap test fail"];
    [DamageItems addObject:@"Lightning damage"];
    [DamageItems addObject:@"Edge protection damage"];
    [DamageItems addObject:@"Coat defect"];
    [DamageItems addObject:@"Erosion/pitting"];
    [DamageItems addObject:@"Component damage"];
    [DamageItems addObject:@"Component missing"];

    
    
    // init rating combobox items
    RatingItems = [[NSMutableArray alloc] initWithCapacity:2];
    activeTextFiledInfo = [[NSMutableDictionary alloc] initWithCapacity:0];
    if(self.SuspendDicInfo) // from existing suspend damage report
    {
        [RatingItems addObject:@"Minor"];
        [RatingItems addObject:@"Significant"];
        currRating = @"Minor";
        
        if (self.suspendedDamageRecords) 
        {
            if(self.suspendedDamageRecords.count ==1) // have only row
            {
                
                NSMutableDictionary *saveRecordZero = (NSMutableDictionary *)[self.suspendedDamageRecords objectAtIndex:0];
                NSLog(@"suspended des:%@",[saveRecordZero description]);
                
                [contentRows addObject:[saveRecordZero objectForKey:@"damage"]];
                int damageTypeIndex  =[self getDamageTypeIndex: [saveRecordZero objectForKey:@"damage"] ];
                NSLog(@"damageTypeIndex:%d",damageTypeIndex);
                // display dynamic fields
                [self damageTypeChangeToTypeIndex:damageTypeIndex];
                
                [contentRows addObject:[saveRecordZero objectForKey:@"cause"]];
                if ([saveRecordZero objectForKey:@"rating"]) {
                    currRating = [saveRecordZero objectForKey:@"rating"];
                }
                
                if ([saveRecordZero objectForKey:@"length"])
                {
                    [activeTextFiledInfo setObject:[saveRecordZero objectForKey:@"length"] forKey:@"length"];
                }
                
                if([saveRecordZero objectForKey:@"width"] )
                {
                    [activeTextFiledInfo setObject:[saveRecordZero objectForKey:@"width"] forKey:@"width"];
                }
                if ([saveRecordZero objectForKey:@"area"] ) {
                    [activeTextFiledInfo setObject:[saveRecordZero objectForKey:@"area"] forKey:@"area"];
                }
                if ([saveRecordZero objectForKey:@"depth"]) {
                    [activeTextFiledInfo setObject:[saveRecordZero objectForKey:@"depth"] forKey:@"depth"];
                }
                if ([saveRecordZero objectForKey:@"distance"] ) {
                    currentDistanceValue = [(NSNumber *)[saveRecordZero objectForKey:@"distance"] floatValue];
                }
                if ([saveRecordZero objectForKey:@"surface"] ) {
                    currentSurfaceSelectedIndex =[(NSNumber*)[saveRecordZero objectForKey:@"surface"] intValue];
                }
                if ([saveRecordZero objectForKey:@"notes"]) {
                    currNotes = [saveRecordZero objectForKey:@"notes"];
                }
                // get photos
                [base64Photos addObject:[saveRecordZero objectForKey:@"photo1"]];
                [base64Photos addObject:[saveRecordZero objectForKey:@"photo2"]];
                [base64Photos addObject:[saveRecordZero objectForKey:@"photo3"]];
                [base64Photos addObject:[saveRecordZero objectForKey:@"photo4"]];
                
            }
            else // have mutil rows is saved to damagereport.plist
            {
                savedDamageRecords = self.suspendedDamageRecords;
                // set flag saved is TRUE
                isSaved = TRUE;
                
                for (int i =0; i< savedDamageRecords.count; i++) {
                      [headerSectionIndexs insertObject:@"10" atIndex:(headerSectionIndexs.count-1)];
                }
                // reset table cells
                [self resetAllCellOfTable];
                // reload table
                currentSaveSection = 0; //alway call when reloadData
                [tblDamageReportTable reloadData];
            }
        }
        
    }
    else // go from new report
    {
        
        [RatingItems addObject:@"Minor"];
        [RatingItems addObject:@"Significant"];
        currRating = @"Minor";
    }

    // init cause combobox items
    CauseItems =[[NSMutableArray alloc] initWithCapacity:0];
    [CauseItems addObject:@"Post Commisioning"];
    [CauseItems addObject:@"Production"];
    [CauseItems addObject:@"Transport"];
    [CauseItems addObject:@"Loading"];
    [CauseItems addObject:@"Installation"];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)backNavigationTapped
{
    NSLog(@"data will be suspended!");
    [self suspendReport];
    [self.navigationController popViewControllerAnimated:YES];
}
//handle surface segment value change
-(IBAction)surfaceSegmet_ValueChange:(UISegmentedControl*)sender
{
    currentSurfaceSelectedIndex = sender.selectedSegmentIndex;
}

-(IBAction)distanceSlider_ValueChange:(UISlider *)sender
{
    currentDistanceValue = sender.value *0.25f;
    
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return headerSectionIndexs.count;
}

// display header section
- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section
{
    int index = [((NSString*)[headerSectionIndexs objectAtIndex:section]) intValue];
    return [sectionNames objectAtIndex:index];
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    //if(section==0) return 2;
    
    return 1; // on each section
}


// Display each cell of table
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d_%d", indexPath.section,indexPath.row];
    UITableViewCell *cell;
    NSArray *nib;
    NSMutableDictionary *saveRecord;
    int index = [((NSString*)[headerSectionIndexs objectAtIndex:indexPath.section]) intValue];
    switch (index) {
        case 0: //distance cell
            
                cell =(DistanceCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
                
                if (cell == nil) {
                    nib = [[NSBundle mainBundle] loadNibNamed:@"DistanceCell"
                                                        owner:self options:nil];
                    for (id oneObject in nib)
                        if ([oneObject isKindOfClass:[DistanceCell class]])
                            cell = (DistanceCell *)oneObject;
                }
                // assign tfDistance
                [((DistanceCell*)cell).slider  addTarget:self action:@selector(distanceSlider_ValueChange:) forControlEvents:UIControlEventValueChanged];
                // retain value of slider when reload table
                if (self.distanceMaxLength)
                   ((DistanceCell*)cell).slider.maximumValue = [self.distanceMaxLength intValue]/0.25f;
                else
                    ((DistanceCell*)cell).slider.maximumValue =  50/0.25f;
            
                
                ((DistanceCell*)cell).slider.value = currentDistanceValue/0.25f;
                
                tfDistance = ((DistanceCell*)cell).textField;
                int value = (int) currentDistanceValue/0.25f;
                [tfDistance setText:[NSString stringWithFormat:@"%0.02f",0.25f*value]];
               
                // set selection type
                cell.selectionStyle = UITableViewCellSelectionStyleNone;

            break;
        case 1: //damage type
        case 2: //cause
            cell  = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if(cell ==nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            }
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
            // Get the object to display and set the value in the cell.
            cell.textLabel.text = [NSString stringWithFormat:@"%@",[contentRows objectAtIndex:index]];
            cell.accessoryView = [[ UIImageView alloc ]initWithImage:[UIImage imageNamed:@"AccessoryDisclosure.png" ]];
            cell.accessoryView.bounds = CGRectMake(0, 0, 25, 25);
            break;
        case 3: // length
        case 4: // width
        case 5: // % area
        case 6: // Depth
         {
              cell = (EnterDataCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
             if (cell == nil)
              {
                           nib = [[NSBundle mainBundle] loadNibNamed:@"EnterDataCell"
                                                                owner:self options:nil];
                            for (id oneObject in nib)
                                if ([oneObject isKindOfClass:[EnterDataCell class]])
                                {
                                    cell = (EnterDataCell *)oneObject;
                                }
            
              }
             
             if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
                ((EnterDataCell*)cell).tfEnterData.keyboardType = UIKeyboardTypeDecimalPad;
             else
                ((EnterDataCell*)cell).tfEnterData.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
             
//             [activeTextFields addObject:((EnterDataCell*)cell).tfEnterData];
             
            switch (index)
            {
                case 3:
                    //NSLog(@"tfLength");
                    tfLength =  ((EnterDataCell*)cell).tfEnterData;
                    tfLength.text = activeTextFiledInfo[@"length"]==nil?@"":activeTextFiledInfo[@"length"];
                    tfLength.tag =0;
                    tfLength.delegate = self;
                    //[activeTextFieldIndexPath addObject:indexPath];
                    //[activeTextFields addObject:tfLength];
                    break;
                case 4:
                    //NSLog(@"tfWidth");
                    tfWidth = ((EnterDataCell*)cell).tfEnterData;
                     tfWidth.text = activeTextFiledInfo[@"width"]==nil?@"":activeTextFiledInfo[@"width"];
                    tfWidth.tag =1;
                    tfWidth.delegate = self;
                    //[activeTextFieldIndexPath addObject:indexPath];
                    //[activeTextFields addObject:tfWidth];
                    break;
                case 5:
                    //NSLog(@"tfArea");
                    tfArea = ((EnterDataCell*)cell).tfEnterData;
                    tfArea.tag =2;
                     tfArea.text = activeTextFiledInfo[@"area"]==nil?@"":activeTextFiledInfo[@"area"];
                    tfArea.delegate = self;
                    //[activeTextFieldIndexPath addObject:indexPath];
                    //[activeTextFields addObject:tfArea];
                    break;
                case 6:
                    //NSLog(@"tfDepth");
                    tfDepth = ((EnterDataCell*)cell).tfEnterData;
                    tfDepth.tag =3;
                    tfDepth.text = activeTextFiledInfo[@"depth"]==nil?@"":activeTextFiledInfo[@"depth"];
                    tfDepth.delegate = self;
                    //[activeTextFieldIndexPath addObject:indexPath];
                    //[activeTextFields addObject:tfDepth];
                    break;
                default:
                    break;
            }
        }
         break;
        case 7: // rating
            // create Cell
            cell  = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if(cell ==nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            }
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
            // Get the object to display and set the value in the cell.
            cell.textLabel.text = currRating;
            cell.accessoryView = [[ UIImageView alloc ]initWithImage:[UIImage imageNamed:@"AccessoryDisclosure.png" ]];
            cell.accessoryView.bounds = CGRectMake(0, 0, 25, 25);
            
            break;

        case 8: //notes
            cell = (TextViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                nib = [[NSBundle mainBundle] loadNibNamed:@"TextViewCell"
                                                    owner:self options:nil];
                for (id oneObject in nib)
                    if ([oneObject isKindOfClass:[TextViewCell class]])
                        cell = (TextViewCell *)oneObject;
                
            }

//            ((TextViewCell*)cell).textView.tag = [activeTextFields count];
//            [activeTextFields addObject:((TextViewCell*)cell).textView];
            // asign to tv nodes
            tvNotes = ((TextViewCell*)cell).textView;
            tvNotes.delegate = self;
            if (currNotes) {
                tvNotes.text = currNotes;
            }
            break;
        case 9: //actions
            cell = (DamageReportButtonCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                nib = [[NSBundle mainBundle] loadNibNamed:@"DamageReportButtonsCell"
                                                    owner:self options:nil];
                for (id oneObject in nib)
                    if ([oneObject isKindOfClass:[DamageReportButtonCell class]])
                        cell = (DamageReportButtonCell *)oneObject;
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            // assign action for buttons
            [((DamageReportButtonCell*)cell).addPhotoButton addTarget:self action:@selector(addPhotoButton_Click:)  forControlEvents:UIControlEventTouchUpInside];
            [((DamageReportButtonCell*)cell).saveButton addTarget:self action:@selector(saveButton_Click:) forControlEvents:UIControlEventTouchUpInside];
            break;
        case 10: //save
            cell = (DamageReportButtonCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                nib = [[NSBundle mainBundle] loadNibNamed:@"SaveSummaryCell"
                                                    owner:self options:nil];
                for (id oneObject in nib)
                    if ([oneObject isKindOfClass:[SaveSummaryCell class]])
                        cell = (SaveSummaryCell *)oneObject;
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            currentSaveSection = indexPath.section - indexOfFirstSaveSection;
            
            NSLog(@"CurrentSaveSection: %d", currentSaveSection);
            
            saveRecord = [savedDamageRecords objectAtIndex:currentSaveSection];
            ((SaveSummaryCell *)cell).distance.text = [saveRecord objectForKey:@"distance"];
            ((SaveSummaryCell *)cell).surface.text = [saveRecord objectForKey:@"surface"];
            ((SaveSummaryCell *)cell).damageType.text = [saveRecord objectForKey:@"damage"];
            
            currentSaveSection ++; //always set currentSaveSection = 0 everytime reload table data
            if (currentSaveSection >= savedDamageRecords.count) currentSaveSection = 0;
            break;
        case 11: //actions
            cell = (DamageReportButtonCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                nib = [[NSBundle mainBundle] loadNibNamed:@"SuppendFinishCell"
                                                    owner:self options:nil];
                for (id oneObject in nib)
                    if ([oneObject isKindOfClass:[SuppendFinishCell class]])
                        cell = (SuppendFinishCell *)oneObject;
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            // assign action for buttons
            [((SuppendFinishCell*)cell).suspendButton addTarget:self action:@selector(suspendButton_Click:) forControlEvents:UIControlEventTouchUpInside];
            [((SuppendFinishCell*)cell).finishButton addTarget:self action:@selector(finishButton_Click:) forControlEvents:UIControlEventTouchUpInside];
            break;
        case 12: // Area
            
            cell =(DistanceCell2*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            
            if (cell == nil) {
                nib = [[NSBundle mainBundle] loadNibNamed:@"DistanceCell2"
                                                    owner:self options:nil];
                for (id oneObject in nib)
                    if ([oneObject isKindOfClass:[DistanceCell2 class]])
                        cell = (DistanceCell2 *)oneObject;
            }
            // assign to segmentation surface
            
            segmentSurface = ((DistanceCell2 *)cell).segmentation;
            [segmentSurface addTarget:self action:@selector(surfaceSegmet_ValueChange:) forControlEvents:UIControlEventValueChanged];
            segmentSurface.selectedSegmentIndex = currentSurfaceSelectedIndex;
            // set selection type
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            break;
            
        default:
            break;
    }
    
    return cell;
}

// change row height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    int index = [((NSString*)[headerSectionIndexs objectAtIndex:indexPath.section]) intValue];
    return [((NSString*)[heighOfRowOnSections objectAtIndex:index]) intValue];
}


// selected specified row event handle
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    int index = [((NSString*)[headerSectionIndexs objectAtIndex:indexPath.section]) intValue];
    switch (index) {
        case 1: // Damage
            mode =0;
            [self showPicker];
            break;
        case 2:
            mode =1; // Cause
            [self showPicker];
            break;
        case 7:
            mode =2; // Rating
            [self showPicker];
            break;
        default:
            break;
    }
}

-(void)showPicker
{
    
    // Scroll table view toi do
    if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPhone)
    {
        [UIView animateWithDuration:0.3f animations:^{
            [view1 setFrame:CGRectMake(0, 160, 320, 260)];
        }];
    }
    else // ipad
    {
        [UIView animateWithDuration:0.3f animations:^{
            [view1 setFrame:CGRectMake(0, 700, 768, 260)];
        }];
        
        
    }
    
    switch (mode) {
        case 0: // damage type
            picker.hidden = NO;
            picker2.hidden = YES;
            picker3.hidden = YES;
            
            [picker reloadAllComponents];
            break;
        case 1: // cause
            picker2.hidden = NO;
            picker.hidden = YES;
            picker3.hidden = YES;
            [picker2 reloadAllComponents];
            break;
        case 2: // rating
            picker3.hidden = NO;
            picker.hidden = YES;
            picker2.hidden = YES;
            [picker3 reloadAllComponents];
            break;
        default:
            break;
    }
    
    
}

-(void)hidePicker
{
    CGRect viewFrame = CGRectMake(0, 420, 320, 260);
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
        viewFrame = CGRectMake(0, 1000, 768, 260);
    [UIView animateWithDuration:0.3f animations:^{
        [view1 setFrame:viewFrame];
    }];
//    activeTextFields = [[NSMutableArray alloc] initWithCapacity:0];
    currentSaveSection = 0; //alway call when reloadData
    [tblDamageReportTable reloadData];
}


#pragma mark -UIPicker Datasource
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    switch (mode) {
        case 0:
            //Damage
        {
            return DamageItems.count;
        }
            break;
        case 1:
            //Cause
        {
            return CauseItems.count;
        }
        default: // Rating
            return RatingItems.count;
            break;
    }
    return 0;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString* title;
    switch (mode) {
        case 0:
            //Access methods
        {
            title = [DamageItems objectAtIndex:row];
        }
            break;
        case 1:
            //Sides
        {
            title = [CauseItems objectAtIndex:row];
        }
            break;
        default: // Rating
            title =[RatingItems objectAtIndex:row];
            break;
    }
    return title;
}


- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    switch (mode) {
        case 0: // Access methods
            [contentRows replaceObjectAtIndex:1 withObject:[DamageItems objectAtIndex:row]];
            [self damageTypeChangeToTypeIndex:row];
            break;
        case 1: // Sides
            [contentRows replaceObjectAtIndex:2 withObject:[CauseItems objectAtIndex:row]];
            break;
        default: // Rating
            currRating = [RatingItems objectAtIndex:row];
            break;
    }
}

-(void)damageTypeChangeToTypeIndex:(int)index
{

    switch (index) {
        case 0: //Rub mark
        case 1:
            headerSectionIndexs = [[NSMutableArray alloc] initWithObjects:
                                   @"0", //distance
                                   @"12",
                                   @"1", //damage
                                   @"2", //cause
                                   @"3",
                                   @"4",
                                   @"6",
                                   @"8", //note
                                   @"9", //action
                                   nil];
            break;
            
        case 2: //gel coat crack
            headerSectionIndexs = [[NSMutableArray alloc] initWithObjects:
                                   @"0",
                                   @"12",
                                   @"1",
                                   @"2",
                                   @"3",
                                   @"4",
                                   @"8",
                                   @"9",
                                   nil];
            break;
        case 3: // Bubble
            headerSectionIndexs = [[NSMutableArray alloc] initWithObjects:
                                   @"0", //distance
                                   @"12",
                                   @"1", //damage
                                   @"2", //cause
                                   @"4",
                                   @"7",
                                   @"8", //note
                                   @"9", //action
                                   nil];
            
            break;
        case 4: //Fissures/holes
        case 5: // Chip
            headerSectionIndexs = [[NSMutableArray alloc] initWithObjects:
                                   @"0", //distance
                                   @"12",
                                   @"1", //damage
                                   @"2", //cause
                                   @"4",
                                   @"8", //note
                                   @"9", //action
                                   nil];
            

            break;
        case 6: // Cast
            headerSectionIndexs = [[NSMutableArray alloc] initWithObjects:
                                   @"0",
                                   @"12",
                                   @"1",
                                   @"2",
                                   @"3",
                                   @"4",
                                   @"7",
                                   @"8",
                                   @"9",
                                   nil];
            
            break;
        case 7: //Delamination
            headerSectionIndexs = [[NSMutableArray alloc] initWithObjects:
                                   @"0",
                                   @"12",
                                   @"1",
                                   @"2",
                                   @"4",
                                   @"5",
                                   @"8",
                                   @"9",
                                   nil];
            break;
        case 8: // Water in blade
        case 9: // Oil in blade
            headerSectionIndexs = [[NSMutableArray alloc] initWithObjects:
                                   @"0",
                                   @"12",
                                   @"1",
                                   @"2",
                                   @"8",
                                   @"9",
                                   nil];
            break;
       case 10: //Tap test fail (debonding)
       case 11: //Lightning damage
       case 12: // Edge protection damage
            headerSectionIndexs = [[NSMutableArray alloc] initWithObjects:
                                   @"0",
                                   @"12",
                                   @"1",
                                   @"2",
                                   @"3",
                                   @"4",
                                   @"8",
                                   @"9",
                                   nil];
            break;
        case 13: //Coat defect
            headerSectionIndexs = [[NSMutableArray alloc] initWithObjects:
                                   @"0",
                                   @"12",
                                   @"1",
                                   @"2",
                                   @"5",
                                   @"8",
                                   @"9",
                                   nil];
            break;
        case 14: //Erosion/pitting
            headerSectionIndexs = [[NSMutableArray alloc] initWithObjects:
                                   @"0",
                                   @"12",
                                   @"1",
                                   @"2",
                                   @"3",
                                   @"4",
                                   @"6",
                                   @"7",
                                   @"8",
                                   @"9",
                                   nil];
            break;
        case 15: //Component damage
        case 16: //Component missing
            headerSectionIndexs = [[NSMutableArray alloc] initWithObjects:
                                   @"0",
                                   @"12",
                                   @"1",
                                   @"2",
                                   @"7",
                                   @"8",
                                   @"9",
                                   nil];
            break;
            
        default:
            break;
    }
    indexOfFirstSaveSection = headerSectionIndexs.count;
    int numberOfSavedRecords = savedDamageRecords.count;
    for (int i=0; i<numberOfSavedRecords; i++)
    {
        [headerSectionIndexs addObject:@"10"];
    }
    [headerSectionIndexs addObject:@"11"];

}
// hide picker when click done
-(IBAction)donePicker_Click:(id)sender
{
    [self hidePicker];
}

-(IBAction)addPhotoButton_Click:(id)sender
{
    NSLog(@"addPhotoButton_Click");
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Add photo" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Use Camera", @"Load From Library", nil];
    [actionSheet showInView:self.view];
}

-(IBAction)saveButton_Click:(id)sender
{
    NSLog(@"addSaveButton_Click");
    
    [headerSectionIndexs insertObject:@"10" atIndex:(headerSectionIndexs.count-1)];
    // save current damage record to list hence using for upload or suspend
    NSMutableDictionary * currDamageReportDic = [self getDamageInfoDict];
    [savedDamageRecords addObject: currDamageReportDic];
    isSaved = TRUE;
    
    // reset table cells
    [self resetAllCellOfTable];
    // reload table
    currentSaveSection = 0; //alway call when reloadData
    [tblDamageReportTable reloadData];
    
}
-(void)suspendReport
{
    NSLog(@"suspendButton_Click");
    if(self.ReportDictInfo) // From new report
    {
        // add new record to newreport table
        // NSString * newreportId = [self.ReportDictInfo objectForKey:@"newreportid"];
        // [self addNewReportPlistDB:@"newreport.plist" ForNewReportId:newreportId];
        // test add to sqlite
        [self addNewreportToDB];
        // test get lastest report id
        NSString * newreportId = [self getLastestNewReportId];
        
        if(!isSaved)
        {
            // add new record to damage report table
            NSMutableDictionary * currRecord = [self getDamageInfoDict];
            //[self addDamgeRecordsToDB:@"damagereport.plist" SavedRecord:currRecord ForNewReport:newreportId];
            [self addDamgeReportToDB:currRecord ForNewReport:newreportId];
            
        }
        else // saved
        {
            // add saved record to damage report table
            for (int i=0; i< savedDamageRecords.count; i++) {
                //[self addDamgeRecordsToDB:@"damagereport.plist" SavedRecord:savedDamageRecords[i] ForNewReport:newreportId];
                [self addDamgeReportToDB:savedDamageRecords[i] ForNewReport:newreportId];
            }
            
        }
        
    }
    else if(self.SuspendDicInfo) // from suspend
    {
        // get newreport id
        NSString * newreportId = [self.SuspendDicInfo objectForKey:@"id"];
        if(!isSaved)
        {
            // get current damage record
            NSMutableDictionary * currRecord = [self getDamageInfoDict];
            // update damage record by newreport id
            [self updateDamgeReportToDB:currRecord ForNewReport:newreportId];
        }
        else
        {
            // add new records only
            for (int i= savedDamageRecords.count-1; i > self.suspendedDamageRecords.count-1; i--)
            {
                //[self addDamgeRecordsToDB:@"damagereport.plist" SavedRecord:savedDamageRecords[i] ForNewReport:newreportId];
                [self addDamgeReportToDB:savedDamageRecords[i] ForNewReport:newreportId];
            }
            
        }
    }
    
}
-(IBAction)suspendButton_Click:(id)sender
{
    [self suspendReport];
    // move to inspect controller
    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:2] animated:YES];
}

// Reset to table to view did load
-(void) resetAllCellOfTable
{

    // Reset dynamic fileds
    for (int i=0; i<4; i++) {
        
        switch (i) {
            case 0:
                if (tfLength) {
                    tfLength.text =@"";
                    [activeTextFiledInfo setObject:tfLength.text forKey:@"length"];
                }
                
                break;
            case 1:
                if (tfWidth) {
                    tfWidth.text =@"";
                    [activeTextFiledInfo setObject:tfWidth.text forKey:@"width"];
                }
                
                break;
            case 2:
                if (tfArea) {
                    tfArea.text =@"";
                    [activeTextFiledInfo setObject:tfArea.text forKey:@"area"];
                }
                
                break;
            case 3:
                if (tfDepth) {
                    tfDepth.text =@"";
                    [activeTextFiledInfo setObject:tfDepth.text forKey:@"depth"];
                }
                
                break;
            default:
                break;
        }
    }
    
    // RESET CONTENT ROWS
    [contentRows addObject:@""];
    [contentRows addObject:@"Rub mark"];
    [contentRows addObject:@"Post commisioning"];
    
    [RatingItems addObject:@"Minor"];
    [RatingItems addObject:@"Significant"];
    currRating = @"Minor";
    // reset distance
//    currentDistanceValue =0;
//    segmentSurface.selectedSegmentIndex =0;
    currNotes =@"";
    
}



-(IBAction)finishButton_Click:(id)sender
{
    NSLog(@"finishButton_Click");
    
    NSString * urlString;
    /*
     //--- replace GET METHOD by POST method
    if(self.ReportDictInfo)
        urlString = [self buildURLToSubmit:YES];
    else
    {
        urlString = [self buildURLToSubmit:NO];
       
    }
    */
    urlString = [NSString stringWithFormat:@"%@%@",kBASE_URL,@"inspect.php"];
    NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    
    for (int i =0; i<base64Photos.count; i++)
    {
        NSString * imgStr = [base64Photos objectAtIndex:i]; // base64 encode string
        // decode to get image data
        //NSData *imageData = [NSData dataFromBase64String:imgStr];
        // GET METHOD
         //urlString = [urlString stringByAppendingFormat:@"&photo%d_filename=photo%d&photo%d_data=%@",i+1,i+1,i+1,imgStr];
         // REPLACE BY POST METHOD
        [request setPostValue:[NSString stringWithFormat:@"photo%d_filename.jpg",i+1] forKey:[NSString stringWithFormat:@"photo%d_filename",i+1]];
        [request setPostValue:imgStr forKey:[NSString stringWithFormat:@"photo%d_data",i+1]];
        
    }
    
    [request setRequestMethod:@"POST"];
    
    NSMutableDictionary * damagePostDic = [[NSMutableDictionary alloc] initWithCapacity:0];
    if(self.ReportDictInfo)
        damagePostDic = [self buildURLPOSTToSubmit:YES];
    else
       damagePostDic = [self buildURLPOSTToSubmit:NO];
    
    [request setPostValue:[damagePostDic objectForKey:@"api"]   forKey:@"api"];
    [request setPostValue:[damagePostDic objectForKey:@"udid"] forKey:@"udid"];
    [request setPostValue:[NSDate date] forKey:@"inspectdate"];
    [request setPostValue:[damagePostDic objectForKey:@"wfid"] forKey:@"wfid"];
    [request setPostValue:[damagePostDic objectForKey:@"wtgid"] forKey:@"wtgid"];
    [request setPostValue:[damagePostDic objectForKey:@"wtgvisid"] forKey:@"wtgvisid"];
    [request setPostValue:[damagePostDic objectForKey:@"blade"] forKey:@"blade"];
    [request setPostValue:[damagePostDic objectForKey:@"generated"] forKey:@"generated"];
    [request setPostValue:[damagePostDic objectForKey:@"access"] forKey:@"access"];
    [request setPostValue:[damagePostDic objectForKey:@"side"] forKey:@"side"];
    [request setPostValue:[damagePostDic objectForKey:@"surface"] forKey:@"surface"];
    [request setPostValue:[damagePostDic objectForKey:@"distance"] forKey:@"distance"];
    [request setPostValue:[damagePostDic objectForKey:@"damage"] forKey:@"damage"];
    [request setPostValue:[damagePostDic objectForKey:@"length"] forKey:@"length"];
    [request setPostValue:[damagePostDic objectForKey:@"width"] forKey:@"width"];
    [request setPostValue:[damagePostDic objectForKey:@"area"] forKey:@"area"];
    [request setPostValue:[damagePostDic objectForKey:@"depth"] forKey:@"depth"];
    [request setPostValue:[damagePostDic objectForKey:@"rating"] forKey:@"rating"];
    [request setPostValue:[damagePostDic objectForKey:@"cause"] forKey:@"cause"];
    [request setPostValue:[damagePostDic objectForKey:@"notes"] forKey:@"note"];
    [request setPostValue:[damagePostDic objectForKey:@"extratech"] forKey:@"extratech"];
    [request setPostValue:[damagePostDic objectForKey:@"extcam"] forKey:@"extcam"];
    
    [request setDelegate:self];
    [request startAsynchronous];
    
}

-(NSString *) buildURLToSubmit:(BOOL) isFromNewReport
{
    NSMutableDictionary * damageDict = [self getDamageInfoDict]; // current damage record
    NSLog(@"damageDict:%@",[damageDict description]);
    
    // submit to server
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText =@"Processing";
    //surface,extcam (new report) ,distance,damage,length,width,area,depth,rating,cause,notes
    NSString * kURLDamageReport = [kBASE_URL stringByAppendingFormat:@"%@",@"inspect.php?api=%@&udid=%@&inspectdate=%@&wfid=%@&wtgid=%@&blade=%@&wtgvisid=%@&generated=%@&access=%@&side=%@&surface=%@&distance=%@&damage=%@&length=%@&width=%@&area=%@&depth=%@&rating=%@&cause=%@&note=%@&extratech=%@&extcam=%@"];
    
    NSString * urlString;
    if (isFromNewReport)
    {
        if (!isSaved)
        {
            urlString = [NSString stringWithFormat:kURLDamageReport,[self.ReportDictInfo objectForKey:@"api"],[self.ReportDictInfo objectForKey:@"udid"],[NSDate date],[self.ReportDictInfo objectForKey:@"wfid"],[self.ReportDictInfo objectForKey:@"wtgid"],[self.ReportDictInfo objectForKey:@"blade"],[self.ReportDictInfo objectForKey:@"wtgvisid"],[self.ReportDictInfo objectForKey:@"generated"],[self.ReportDictInfo objectForKey:@"access"],[self.ReportDictInfo objectForKey:@"side"],[damageDict objectForKey:@"surface"],[damageDict objectForKey:@"distance"],[damageDict objectForKey:@"damage"],[damageDict objectForKey:@"length"],[damageDict objectForKey:@"width"],[damageDict objectForKey:@"area"],[damageDict objectForKey:@"depth"],[damageDict objectForKey:@"rating"],[damageDict objectForKey:@"cause"],[damageDict objectForKey:@"notes"],[ReportDictInfo objectForKey:@"extratech"],[ReportDictInfo objectForKey:@"extcam"]];
        }
        else
        {
              NSMutableDictionary * savedDic = [savedDamageRecords objectAtIndex:submitTimes];
              urlString = [NSString stringWithFormat:kURLDamageReport,[self.SuspendDicInfo objectForKey:@"api"],[self.SuspendDicInfo objectForKey:@"udid"],[NSDate date],[self.SuspendDicInfo objectForKey:@"wfid"],[self.SuspendDicInfo objectForKey:@"wtgid"],[self.SuspendDicInfo objectForKey:@"blade"],[self.SuspendDicInfo objectForKey:@"wtgvisid"],[self.SuspendDicInfo objectForKey:@"generated"],[self.SuspendDicInfo objectForKey:@"access"],[self.SuspendDicInfo objectForKey:@"side"],[savedDic objectForKey:@"surface"],[savedDic objectForKey:@"distance"],[savedDic objectForKey:@"damage"],[savedDic objectForKey:@"length"],[savedDic objectForKey:@"width"],[savedDic objectForKey:@"area"],[savedDic objectForKey:@"depth"],[savedDic objectForKey:@"rating"],[savedDic objectForKey:@"cause"],[savedDic objectForKey:@"notes"],[ReportDictInfo objectForKey:@"extratech"],[ReportDictInfo objectForKey:@"extcam"]];
        }
        
    }
    else // from suspend
    {
       
        NSMutableDictionary *suspendRecord = (NSMutableDictionary *)[self.suspendedDamageRecords objectAtIndex:submitTimes];
         urlString = [NSString stringWithFormat:kURLDamageReport,[self.SuspendDicInfo objectForKey:@"api"],[self.SuspendDicInfo objectForKey:@"udid"],[NSDate date],[self.SuspendDicInfo objectForKey:@"wfid"],[self.SuspendDicInfo objectForKey:@"wtgid"],[self.SuspendDicInfo objectForKey:@"blade"],[self.SuspendDicInfo objectForKey:@"wtgvisid"],[self.SuspendDicInfo objectForKey:@"generated"],[self.SuspendDicInfo objectForKey:@"access"],[self.SuspendDicInfo objectForKey:@"side"],[suspendRecord objectForKey:@"surface"],[suspendRecord objectForKey:@"distance"],[suspendRecord objectForKey:@"damage"],[suspendRecord objectForKey:@"length"],[suspendRecord objectForKey:@"width"],[suspendRecord objectForKey:@"area"],[suspendRecord objectForKey:@"depth"],[suspendRecord objectForKey:@"rating"],[suspendRecord objectForKey:@"cause"],[suspendRecord objectForKey:@"notes"],[self.SuspendDicInfo objectForKey:@"extratech"],[self.SuspendDicInfo objectForKey:@"extcam"]];
    }
        
    return urlString;
}


-(NSMutableDictionary *) buildURLPOSTToSubmit:(BOOL) isFromNewReport
{
    NSMutableDictionary * rv = [[NSMutableDictionary alloc] initWithCapacity:0];
    
    NSMutableDictionary * damageDict = [self getDamageInfoDict]; // current damage record
    NSLog(@"damageDict:%@",[damageDict description]);
    
    if (isFromNewReport)
    {
        if (!isSaved)
        {
            [rv setObject:[self.ReportDictInfo objectForKey:@"api"] forKey:@"api"];
            [rv setObject: [self.ReportDictInfo objectForKey:@"udid"] forKey:@"udid"];
            [rv setObject: [NSDate date] forKey:@"inspectdate"];
            [rv setObject:[self.ReportDictInfo objectForKey:@"wfid"] forKey:@"wfid"];
            [rv setObject:[self.ReportDictInfo objectForKey:@"wtgid"] forKey:@"wtgid"];
            [rv setObject:[self.ReportDictInfo objectForKey:@"blade"] forKey:@"blade"];
            [rv setObject:[self.ReportDictInfo objectForKey:@"wtgvisid"] forKey:@"wtgvisid"];
            [rv setObject: [self.ReportDictInfo objectForKey:@"generated"] forKey:@"generated"];
            [rv setObject:[self.ReportDictInfo objectForKey:@"access"] forKey:@"access"];
            [rv setObject:[self.ReportDictInfo objectForKey:@"side"] forKey:@"side"];
            [rv setObject:[damageDict objectForKey:@"surface"] forKey:@"surface"];
            [rv setObject: [damageDict objectForKey:@"distance"] forKey:@"distance"];
            [rv setObject:[damageDict objectForKey:@"damage"] forKey:@"damage"];
            [rv setObject:[damageDict objectForKey:@"length"] forKey:@"length"];
            [rv setObject:[damageDict objectForKey:@"width"] forKey:@"width"];
            [rv setObject:[damageDict objectForKey:@"area"] forKey:@"area"];
            [rv setObject:[damageDict objectForKey:@"depth"] forKey:@"depth"];
            [rv setObject:[damageDict objectForKey:@"rating"] forKey:@"rating"];
            [rv setObject:[damageDict objectForKey:@"cause"] forKey:@"cause"];
            [rv setObject:[damageDict objectForKey:@"notes"] forKey:@"notes"];
            [rv setObject:[ReportDictInfo objectForKey:@"extratech"] forKey:@"extratech"];
            [rv setObject:[ReportDictInfo objectForKey:@"extcam"] forKey:@"extcam"];
            
        }
        else
        {
            NSMutableDictionary * savedDic = [savedDamageRecords objectAtIndex:submitTimes];
            
            [rv setObject:[self.ReportDictInfo objectForKey:@"api"] forKey:@"api"];
            [rv setObject: [self.ReportDictInfo objectForKey:@"udid"] forKey:@"udid"];
            [rv setObject: [NSDate date] forKey:@"inspectdate"];
            [rv setObject:[self.ReportDictInfo objectForKey:@"wfid"] forKey:@"wfid"];
            [rv setObject:[self.ReportDictInfo objectForKey:@"wtgid"] forKey:@"wtgid"];
            [rv setObject:[self.ReportDictInfo objectForKey:@"blade"] forKey:@"blade"];
            [rv setObject:[self.ReportDictInfo objectForKey:@"wtgvisid"] forKey:@"wtgvisid"];
            [rv setObject: [self.ReportDictInfo objectForKey:@"generated"] forKey:@"generated"];
            [rv setObject:[self.ReportDictInfo objectForKey:@"access"] forKey:@"access"];
            [rv setObject:[self.ReportDictInfo objectForKey:@"side"] forKey:@"side"];
            [rv setObject:[savedDic objectForKey:@"surface"] forKey:@"surface"];
            [rv setObject: [savedDic objectForKey:@"distance"] forKey:@"distance"];
            [rv setObject:[savedDic objectForKey:@"damage"] forKey:@"damage"];
            [rv setObject:[savedDic objectForKey:@"length"] forKey:@"length"];
            [rv setObject:[savedDic objectForKey:@"width"] forKey:@"width"];
            [rv setObject:[savedDic objectForKey:@"area"] forKey:@"area"];
            [rv setObject:[savedDic objectForKey:@"depth"] forKey:@"depth"];
            [rv setObject:[savedDic objectForKey:@"rating"] forKey:@"rating"];
            [rv setObject:[savedDic objectForKey:@"cause"] forKey:@"cause"];
            [rv setObject:[savedDic objectForKey:@"notes"] forKey:@"notes"];
            [rv setObject:[self.ReportDictInfo objectForKey:@"extratech"] forKey:@"extratech"];
            [rv setObject:[self.ReportDictInfo objectForKey:@"extcam"] forKey:@"extcam"];
            
        }
        
    }
    else // from suspend
    {
        
        NSMutableDictionary *suspendRecord = (NSMutableDictionary *)[self.suspendedDamageRecords objectAtIndex:submitTimes];
        
        [rv setObject:[self.SuspendDicInfo objectForKey:@"api"] forKey:@"api"];
        [rv setObject: [self.SuspendDicInfo objectForKey:@"udid"] forKey:@"udid"];
        [rv setObject: [NSDate date] forKey:@"inspectdate"];
        [rv setObject:[self.SuspendDicInfo objectForKey:@"wfid"] forKey:@"wfid"];
        [rv setObject:[self.SuspendDicInfo objectForKey:@"wtgid"] forKey:@"wtgid"];
        [rv setObject:[self.SuspendDicInfo objectForKey:@"blade"] forKey:@"blade"];
        [rv setObject:[self.SuspendDicInfo objectForKey:@"wtgvisid"] forKey:@"wtgvisid"];
        [rv setObject: [self.SuspendDicInfo objectForKey:@"generated"] forKey:@"generated"];
        [rv setObject:[self.SuspendDicInfo objectForKey:@"access"] forKey:@"access"];
        [rv setObject:[self.SuspendDicInfo objectForKey:@"side"] forKey:@"side"];
        [rv setObject:[suspendRecord objectForKey:@"surface"] forKey:@"surface"];
        [rv setObject: [suspendRecord objectForKey:@"distance"] forKey:@"distance"];
        [rv setObject:[suspendRecord objectForKey:@"damage"] forKey:@"damage"];
        [rv setObject:[suspendRecord objectForKey:@"length"] forKey:@"length"];
        [rv setObject:[suspendRecord objectForKey:@"width"] forKey:@"width"];
        [rv setObject:[suspendRecord objectForKey:@"area"] forKey:@"area"];
        [rv setObject:[suspendRecord objectForKey:@"depth"] forKey:@"depth"];
        [rv setObject:[suspendRecord objectForKey:@"rating"] forKey:@"rating"];
        [rv setObject:[suspendRecord objectForKey:@"cause"] forKey:@"cause"];
        [rv setObject:[suspendRecord objectForKey:@"notes"] forKey:@"notes"];
        [rv setObject:[self.SuspendDicInfo objectForKey:@"extratech"] forKey:@"extratech"];
        [rv setObject:[self.SuspendDicInfo objectForKey:@"extcam"] forKey:@"extcam"];
        
    }
    
    return rv;
}


#pragma mark - UIActionSheetDelegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex)
    {
        case 0:
            NSLog(@"Camera");
            [self getPhotoForAction:buttonIndex];
            break;
        case 1:
            NSLog(@"Library");
            [self getPhotoForAction:buttonIndex];
            break;
        case 2:
            NSLog(@"Cancel");
            break;
            
    }
    
}

-(void) getPhotoForAction:(int) action_index
{
	UIImagePickerController * photoPicker = [[UIImagePickerController alloc] init];
	photoPicker.delegate = self;
    
	if(action_index==0) {
        photoPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
		
	} else {
		photoPicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
	}
    
	[self presentModalViewController:photoPicker animated:YES];
}


#pragma UIImagePickerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissModalViewControllerAnimated:YES];
	UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    if (base64Photos.count < 4) {
        // endcode image to base64 string
        NSData * imageData = UIImageJPEGRepresentation(image, kPhotoCompressionRate);
        NSString * encodeBase64 =[imageData base64EncodedString];
        [base64Photos addObject:encodeBase64];
        
    }
    
}

#pragma mark - textfield keyboard
-(void)backgroundTapped
{
      
    [self.view endEditing:YES];
    [self saveValueForActiveTextFields];
    // reset postion for tableview
    if (tableISRESIZED)
    {
        tblDamageReportTable.frame = CGRectMake(tblDamageReportTable.frame.origin.x,tblDamageReportTable.frame.origin.y, tblDamageReportTable.frame.size.width, self.view.frame.size.height);
        tableISRESIZED = FALSE;
    }
}

#pragma  UITextFieldDelegate
// implement textfile delegate
//- (BOOL)textFieldShouldReturn:(UITextField *)textField
//{
//    
//    [textField resignFirstResponder];
//    
//    /*
//    NSLog(@"textField.tag:%d",textField.tag);
//    
//    NSInteger nextTag = textField.tag + 1;
//    
//    // Try to find next responder
//    if (nextTag > activeTextFields.count-1)
//        return YES;
//    
//    UIResponder *nextResponder = [activeTextFields objectAtIndex:nextTag];
//    if (nextResponder) {
//        [nextResponder becomeFirstResponder];
//    }
//    */
//    
//    [self saveValueForActiveTextFields];
//    // reset postion for tableview
//    if (tableISRESIZED)
//    {
//         tblDamageReportTable.frame = CGRectMake(tblDamageReportTable.frame.origin.x,tblDamageReportTable.frame.origin.y, tblDamageReportTable.frame.size.width, tblDamageReportTable.frame.size.height*2);
//        tableISRESIZED = FALSE;
//    }
//   
//    
//    return YES;
//}


-(void)textFieldDidBeginEditing:(UITextField *)textField
{
       // Scroll table view toi do
    CGPoint point = [textField.superview convertPoint:textField.frame.origin toView:tblDamageReportTable];
    NSIndexPath *indexPath = [tblDamageReportTable indexPathForRowAtPoint:point];
    NSLog(@"row:%d",indexPath.row);
    NSLog(@"section:%d",indexPath.section);
    [tblDamageReportTable scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewRowAnimationTop animated:YES];
    
  
}



-(void)textFieldDidEndEditing:(UITextField *)textField
{
    // Set value for activeTextFieldInfo
    [self saveValueForActiveTextFields];
   
    [textField resignFirstResponder];
    
}


-(void) saveValueForActiveTextFields
{
    // Set value for activeTextFieldInfo
    for (int i=0; i<4; i++) {
        
        switch (i) {
            case 0:
                if (tfLength) {
                    [activeTextFiledInfo setObject:tfLength.text forKey:@"length"];
                }
                
                break;
            case 1:
                if (tfWidth) {
                    [activeTextFiledInfo setObject:tfWidth.text forKey:@"width"];
                }
                
                break;
            case 2:
                if (tfArea) {
                    [activeTextFiledInfo setObject:tfArea.text forKey:@"area"];
                }
                
                break;
            case 3:
                if (tfDepth) {
                    [activeTextFiledInfo setObject:tfDepth.text forKey:@"depth"];
                }
                
                break;
            default:
                break;
        }
    }
    
}

-(void) textViewDidBeginEditing:(UITextView *)textView
{
    
    // Scroll table view toi do
    CGPoint point = [textView.superview convertPoint:textView.frame.origin toView:tblDamageReportTable];
    NSIndexPath *indexPath = [tblDamageReportTable indexPathForRowAtPoint:point];
    [tblDamageReportTable scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewRowAnimationTop animated:YES];

}

-(void)textViewDidEndEditing:(UITextView *)textView
{
    currNotes = tvNotes.text;
    if (tableISRESIZED)
    {
         tblDamageReportTable.frame = CGRectMake(tblDamageReportTable.frame.origin.x,tblDamageReportTable.frame.origin.y, tblDamageReportTable.frame.size.width, self.view.frame.size.height);
        tableISRESIZED = FALSE;
    }
}

// hide textview
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if([text isEqualToString:@"\n"])
        [textView resignFirstResponder];
    return YES;
}



/*
- (void)registerForKeyboardNotifications {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasHidden:)
                                                 name:UIKeyboardDidHideNotification object:nil];
}

- (void)keyboardWasShown:(NSNotification *)aNotification {
    CGRect keyboardBounds;
    [[aNotification.userInfo valueForKey:UIKeyboardBoundsUserInfoKey] getValue: &keyboardBounds];
    keyboardHeight = keyboardBounds.size.height;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationBeginsFromCurrentState:YES];
    tblDamageReportTable.contentInset = UIEdgeInsetsMake(0, 0, keyboardBounds.size.height, 0);
    [UIView commitAnimations];
    [tblDamageReportTable scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[items count] inSection:0]
                     atScrollPosition:UITableViewScrollPositionMiddle
                             animated:YES];
}

- (void)keyboardWasHidden:(NSNotification *)aNotification {
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationBeginsFromCurrentState:YES];
    tblDamageReportTable.contentInset = UIEdgeInsetsZero;
    [UIView commitAnimations];
}
*/

#pragma  DB processing

// Get current damage report on GUI
-(NSMutableDictionary *) getDamageInfoDict
{
    //surface,extcam (new report) ,distance,damage,length,width,area,depth,rating,cause,notes
    NSString *surface =@"";
    switch (segmentSurface.selectedSegmentIndex) {
        case 0:
            surface = @"Surface";
            break;
        case 1:
            surface = @"Leading";
            break;
        default:
            surface =@"Trailing";
            break;
    }
    NSString * distance = tfDistance.text;
    NSString * damage = [contentRows objectAtIndex:1];
    NSString * cause = [contentRows objectAtIndex:2];
    NSString * length = @"";
    if (tfLength) {
        length = tfLength.text;
    }
    NSString * width =@"";
    if (tfWidth) {
        width = tfWidth.text;
    }
    NSString * area =@"";
    if (tfArea) {
        area=tfArea.text;
    }
    NSString * depth=@"";
    if (tfDepth) {
        depth = tfDepth.text;
    }
    NSString * rating=currRating;
    NSString *notes=@"";
    if (tvNotes) {
        notes = tvNotes.text;
    }
    
    NSMutableDictionary * damageDict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [damageDict setObject:surface forKey:@"surface"];
    [damageDict setObject:distance forKey:@"distance"];
    [damageDict setObject:damage forKey:@"damage"];
    [damageDict setObject:cause forKey:@"cause"];
    [damageDict setObject:length forKey:@"length"];
    [damageDict setObject:width forKey:@"width"];
    [damageDict setObject:area forKey:@"area"];
    [damageDict setObject:depth forKey:@"depth"];
    [damageDict setObject:rating forKey:@"rating"];
    [damageDict setObject:notes forKey:@"notes"];
    
    return damageDict;
}


//---------------------------------------------- NEW CODE USE SQLITE ---------------------------------------------
// get DB path
-(NSString *) getDatabasePath
{
    // get document path
    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
    // appending database name path
    NSString *databasePath = [documentsPath stringByAppendingPathComponent:kDataBaseName];
    
    return databasePath;
}

// get lastest newreport id
-(NSString *) getLastestNewReportId
{
    // get database path
    NSString *databasePath =[self getDatabasePath];
    NSLog(@"databasePath:%@",databasePath);
    // get newreport id
    NSString *newreportidStr =  [DBProcessing getLastestNewreportID:databasePath];
    
    return newreportidStr;
}

//add newreport record to db
-(void) addNewreportToDB
{
    // get database path
    NSString *databasePath = [self getDatabasePath];
    NSLog(@"databasePath:%@",databasePath);
    // add new report record
    [DBProcessing addNewreport:self.ReportDictInfo onDataBase:databasePath];

}

/// add damage records according to newreport id to DB
-(void) addDamgeReportToDB:(NSMutableDictionary *) damageRecord ForNewReport:(NSString *) newreportID
{
    // get database path
    NSString *databasePath = [self getDatabasePath];
    NSLog(@"databasePath:%@",databasePath);
    // add new damage report
    [DBProcessing addDamagereport:damageRecord  withNewreportID:newreportID onDataBase:databasePath];
    
}

/// add damage records according to newreport id to DB
-(void) updateDamgeReportToDB:(NSMutableDictionary *) damageRecord ForNewReport:(NSString *) newreportID
{
    // get database path
    NSString *databasePath = [self getDatabasePath];
    NSLog(@"databasePath:%@",databasePath);
    // update existing damage report
    [DBProcessing updateDamagereport:damageRecord withNewreportID:newreportID onDataBase:databasePath];
    
}

// delete newreport and relative damage records on DB
-(void) deleteSuspendRecordsOnDBByNewreportID:(NSString *) newreportID
{
    // get database path
    NSString *databasePath = [self getDatabasePath];
    NSLog(@"databasePath:%@",databasePath);
    // delete newreport
    [DBProcessing deleteNewreportById:newreportID OnDB:databasePath];
    // delete damage records
    [DBProcessing deleteDamageReportByNewreportId:newreportID OnDB:databasePath];
}


//----------------------------OLD CODE USE PLIST ---------------------------------------------------------------

// Supsend not saved
-(void) addNewReportPlistDB:(NSString *) filePath ForNewReportId:(NSString *) newreportid
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *documentsPath = [paths objectAtIndex:0];
    
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:filePath];
    
    NSMutableArray *newReport = [NSMutableArray arrayWithContentsOfFile:plistPath];
    
    
    if (nil == newReport) {
        newReport = [[NSMutableArray alloc] initWithCapacity:0];
    }
    
    NSMutableDictionary *array = [[NSMutableDictionary alloc]init];
    
    [array setObject:newreportid forKey:@"newreportid"];
    [array setObject:[self.ReportDictInfo objectForKey:@"api"] forKey:@"api"];
    [array setObject:[self.ReportDictInfo objectForKey:@"udid"] forKey:@"udid"];
    [array setObject:[self.ReportDictInfo objectForKey:@"wfid"] forKey:@"wfid"];
    [array setObject:[self.ReportDictInfo objectForKey:@"wtgid"] forKey:@"wtgid"];
    [array setObject:[self.ReportDictInfo objectForKey:@"wtgvisid"] forKey:@"wtgvisid"];
    [array setObject:[self.ReportDictInfo objectForKey:@"access"] forKey:@"access"];
    [array setObject:[self.ReportDictInfo objectForKey:@"blade"] forKey:@"blade"];
    [array setObject:[self.ReportDictInfo objectForKey:@"side"] forKey:@"side"];
    
    [newReport addObject:array];
    [newReport writeToFile:plistPath atomically: TRUE];
    
}


// when suspend
-(void) addDamgeRecordsToDB:(NSString *) filePath SavedRecord:(NSMutableDictionary *) damageRecord ForNewReport:(NSString *) newreportID
{
    // write damage report to plist database
    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *documentsPath = [paths objectAtIndex:0];
    
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:filePath];
    
    NSMutableArray *damageReport = [NSMutableArray arrayWithContentsOfFile:plistPath];
    
    
    if (nil == damageReport) {
        damageReport = [[NSMutableArray alloc] initWithCapacity:0];
    }
    
    /*
     access = Rope;
     api = xd7er2;
     blade = A;
     generated = "";
     side = "Tension side";
     udid = 0625dc0d8b495f4c80044508792a44cb00000000;
     wfid = "";
     wtgid = "";
     wtgvisid = test;
     
     area = "";
     cause = "Post commisioning";
     damage = "Rub mark";
     depth = 56;
     distance = "12.25";
     length = 54;
     notes = Thenbh;
     surface = Leading;
     width = 65;
     
     */
    
    NSMutableDictionary *array = [[NSMutableDictionary alloc]init];
    // NSMutableDictionary * currDamageReportDic = [self getDamageInfoDict];
    [array setObject:newreportID forKey:@"newreportid"];
    [array setObject:[damageRecord objectForKey:@"distance"] forKey:@"distance"];
    [array setObject:[damageRecord objectForKey:@"surface"] forKey:@"surface"];
    [array setObject:[damageRecord objectForKey:@"damage"] forKey:@"damage"];
    [array setObject:[damageRecord objectForKey:@"cause"] forKey:@"cause"];
    [array setObject:[damageRecord objectForKey:@"length"] forKey:@"length"];
    [array setObject:[damageRecord objectForKey:@"width"] forKey:@"width"];
    [array setObject:[damageRecord objectForKey:@"area"] forKey:@"area"];
    [array setObject:[damageRecord objectForKey:@"depth"] forKey:@"depth"];
    [array setObject:[damageRecord objectForKey:@"notes"] forKey:@"notes"];
    
    [damageReport addObject:array];
    [damageReport writeToFile:plistPath atomically: TRUE];
}




#pragma ASIHTTP Request
// ASIHTTP Request
-(void)requestFinished:(ASIHTTPRequest *)request
{
    
    NSLog(@"request:%@",[request.url description]);
    
    if (request.responseStatusCode == 400) {
        NSLog(@"Invalid code");
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Damage Report" message:@"Invalid code" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        
    } else if (request.responseStatusCode == 403) {
        NSLog(@"Code already used");
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Damage Report" message:@"Code already used" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        
    } else if (request.responseStatusCode == 200) {
        NSString *responseString = [request responseString];
        NSLog(@"response string:%@",responseString);
        // SUCCESS, ERROR, NO ACCESS, INVALID ACCOUNT
        if([responseString isEqualToString:@"SUCCESS"])
        {
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"DamageReport" message:@"SUCCESS" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            
            // continue submit if is saved data have remain
            submitTimes++;
            if (submitTimes < savedDamageRecords.count)
            {
                [self finishButton_Click:nil];
            }
            else
            {
                
                if(self.SuspendDicInfo) // go to from suspend
                {
                   // delete newreport and relative damage reports
                    [self deleteSuspendRecordsOnDBByNewreportID:[self.SuspendDicInfo objectForKey:@"id"]];
                }
                // goto new report screen
                [self.navigationController popViewControllerAnimated:YES];
//                [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:2] animated:YES];
            }
                

        }
        else if([responseString isEqualToString:@"ACCESS ERROR"])
        {
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"DamageReport" message:@"ACCESS ERROR" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
        }
        else if([responseString isEqualToString:@"NO ACCESS"])
        {
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"DamageReport" message:@"NO ACCESS" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
        }
        else if([responseString isEqualToString:@"INVALID ACCOUNT"])
        {
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"DamageReport" message:@"INVALID ACCOUNT" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
        }
        else
        {
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"DamageReport" message:@"NOT SUCCESS" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
        }

    } else {
        NSLog(@"Unexpected error");
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Damage Report" message:@"Unexpected error" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"error:%@",error.localizedDescription);
    NSLog(@"url:%@", [request.url description]);
    
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Login" message:error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
}

@end
